﻿using Microsoft.Extensions.Options;
using System.Text;
using Volo.Abp.DependencyInjection;

namespace FlyingEye.SignalRHubs
{
    public class HubJwtTokenParser : ISingletonDependency
    {
        private readonly SignalRAuthenticationOptions _options;

        public HubJwtTokenParser(IOptions<SignalRAuthenticationOptions> options)
        {
            _options = options.Value;
        }

        /// <summary>
        /// 这个方法不能放在 DeviceHub 中，否则 SignalR 时，注册服务会报错。
        /// 好像是 System.IdentityModel.Tokens.Jwt Microsoft.IdentityModel.Tokens 依赖出了问题，
        /// 我也不知道原因是什么。
        /// </summary>
        public bool TryParseResourceIdFromToken(string token, out string resourceId)
        {
            var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var validationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SecretKey)),
                ValidateIssuer = true,
                ValidIssuer = _options.Issuer,
                ValidateAudience = true,
                ValidAudience = _options.Audience,
                ValidateLifetime = false,
            };

            try
            {
                // 验证 Token
                var principal = tokenHandler.ValidateToken(token, validationParameters, out _);

                // 提取 resourceId
                var value = principal.FindFirst("resourceId")?.Value;

                resourceId = value ?? string.Empty;

                return !string.IsNullOrWhiteSpace(value);
            }
            catch (Exception)
            {
                resourceId = string.Empty;
                return false;
            }
        }

    }
}
